<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import deliveryAddrApi from '@/api/deliveryAddr_api.js'
import userApi from '@/api/user_api.js'

// 表格数据
const tableData = ref([])
const total = ref(0)
// 定义对话框的显示状态
const editWinVisible = ref(false)
const addWinVisible = ref(false)
// 查询条件
const searchObj = ref({
  current: 1,
  limit: 10,
  id: '',
  user_id: '',
  receiver_name: '',
  receiver_phone: '',
  detail_addr: '',
  is_default: '',
})

// 要修改或者新增的数据
const obj = ref({})

// 用户名到用户ID的映射
const userMap = ref({})

// 获取用户信息
const getUserInfo = async (userId) => {
  if (!userMap.value[userId]) {
    try {
      const userResult = await userApi.getUserById(userId)
      if (userResult && userResult.username) {
        userMap.value[userId] = userResult.username
      }
    } catch (error) {
      console.error(`获取用户${userId}信息失败:`, error)
    }
  }
  return userMap.value[userId]
}

// 查询地址列表
const search = async () => {
    // 处理查询参数
    const queryParams = { ...searchObj.value };
    // 如果有用户名查询条件，先查询用户ID
    if (searchObj.value.username) {
      try {
        // 使用用户分页接口查找用户
        const userResult = await userApi.getUserPage(1, 100, { username: searchObj.value.username });
        if (userResult && userResult.records && userResult.records.length > 0) {
          // 找到匹配的用户，使用第一个匹配用户的ID进行查询
          queryParams.user_id = userResult.records[0].id;
        } else {
          // 没有找到匹配的用户，设置一个不可能存在的用户ID
          queryParams.user_id = -1;
        }
      } catch (error) {
        console.error('查询用户信息失败:', error);
        ElMessage.error("查询用户信息失败");
      }
    }

    console.log('发送的查询参数:', queryParams)
    const result = await deliveryAddrApi.getAddrPage(searchObj.value.current, searchObj.value.limit, queryParams);
    console.log('收到的响应数据:', result)

    // 处理地址数据，获取用户名
    if (result.records) {
      for (let i = 0; i < result.records.length; i++) {
        const addr = result.records[i];

        // 获取用户名
        if (addr.user_id && !userMap.value[addr.user_id]) {
          await getUserInfo(addr.user_id)
        }
        addr.username = userMap.value[addr.user_id] || addr.user_id;
      }
    }
    //从Result中提取分页数据
    tableData.value = result.records
    total.value = result.total
}

// 页面加载完成后查询数据
onMounted(() => {
  search()
})

// 重置查询条件
const resetSearch = () => {
  searchObj.value.id = ''
  searchObj.value.user_id = ''
  searchObj.value.username = ''
  searchObj.value.receiver_name = ''
  searchObj.value.receiver_phone = ''
  searchObj.value.detail_addr = ''
  searchObj.value.is_default = ''
  searchObj.value.current = 1
  search()
}

// 分页大小改变
const handleSizeChange = () => {
  search()
}

// 当前页改变
const handleCurrentChange = () => {
  search()
}

// 处理查询
const handlerSearch = () => {
  searchObj.value.current = 1
  search();
}

// 处理编辑
const handleEdit = (index, row) => {
  obj.value = { ...row }
  editWinVisible.value = true
}

// 编辑对话框的取消按钮点击事件
const editCancel = () => {
  obj.value = {}
  editWinVisible.value = false
}

// 编辑对话框的提交按钮点击事件
const editCommit = async () => {
    await deliveryAddrApi.updateAddr(obj.value)
    await search()
    editWinVisible.value = false
    ElMessage.success('更新成功')
}

// 处理添加
const handlerAdd = () => {
  obj.value = {}
  addWinVisible.value = true
}

// 新增对话框的取消按钮点击事件
const addCancel = () => {
  obj.value = {}
  addWinVisible.value = false
}

// 新增对话框的提交按钮点击事件
const addCommit = async () => {
    await deliveryAddrApi.addAddr(obj.value)
    await search()
    addWinVisible.value = false
}
// 处理删除
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该行数据吗?',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(async () => {
        await deliveryAddrApi.deleteAddr(row.id)
        // 重新加载数据
        searchObj.value.current = 1
        await search()
      })
      .catch(() => {
      })
}
// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  return dateTimeStr.replace('T', ' ')
}
</script>

<template>
  <div class="delivery-addr-management">
    <!-- 查询条件 -->
    <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top:10px">
<!--      <el-form-item label="用户ID">-->
<!--        <el-input v-model="searchObj.user_id" placeholder="请输入用户ID" clearable/>-->
<!--      </el-form-item>-->
      <el-form-item label="用户名">
        <el-input v-model="searchObj.username" placeholder="请输入用户名" clearable/>
      </el-form-item>
      <el-form-item label="收货人">
        <el-input v-model="searchObj.receiver_name" placeholder="请输入收货人姓名" clearable/>
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="searchObj.receiver_phone" placeholder="请输入电话号码" clearable/>
      </el-form-item>
      <el-form-item label="是否默认">
        <el-select v-model="searchObj.is_default" placeholder="请选择是否默认" clearable>
          <el-option label="是" :value="1"></el-option>
          <el-option label="否" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlerSearch">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="resetSearch">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlerAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <!-- 地址表格 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="地址ID" width="80"></el-table-column>
<!--      <el-table-column prop="user_id" label="用户ID" width="80"></el-table-column>-->
      <el-table-column prop="username" label="用户名" width="120">
        <template #default="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column prop="receiver_name" label="收货人" width="100"></el-table-column>
      <el-table-column prop="receiver_phone" label="联系电话" width="120"></el-table-column>
      <el-table-column prop="detail_addr" label="详细地址"></el-table-column>
      <el-table-column prop="is_default" label="是否默认" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.is_default === 1 ? 'success' : 'info'">
            {{ scope.row.is_default === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column prop="update_time" label="更新时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.update_time) }}
        </template>
      </el-table-column>
      <el-table-column label="处理按钮" width="150">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :page-sizes="[10, 20, 50, 100]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 编辑对话框 -->
    <el-dialog v-model="editWinVisible" title="编辑地址" width="500">
      <el-form :model="obj">
        <el-form-item label="用户ID" :label-width="100">
          <el-input v-model.number="obj.user_id" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="收货人" :label-width="100">
          <el-input v-model="obj.receiver_name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="联系电话" :label-width="100">
          <el-input v-model="obj.receiver_phone" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="省份" :label-width="100">
          <el-input v-model="obj.province" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="城市" :label-width="100">
          <el-input v-model="obj.city" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="区县" :label-width="100">
          <el-input v-model="obj.district" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="详细地址" :label-width="100">
          <el-input v-model="obj.detail_addr" type="textarea" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="是否默认" :label-width="100">
          <el-radio-group v-model="obj.is_default">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editCancel">取消</el-button>
          <el-button type="primary" @click="editCommit">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增对话框 -->
    <el-dialog v-model="addWinVisible" title="新增地址" width="500">
      <el-form :model="obj">
        <el-form-item label="用户ID" :label-width="100">
          <el-input v-model.number="obj.user_id" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="收货人" :label-width="100">
          <el-input v-model="obj.receiver_name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="联系电话" :label-width="100">
          <el-input v-model="obj.receiver_phone" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="省份" :label-width="100">
          <el-input v-model="obj.province" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="城市" :label-width="100">
          <el-input v-model="obj.city" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="区县" :label-width="100">
          <el-input v-model="obj.district" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="详细地址" :label-width="100">
          <el-input v-model="obj.detail_addr" type="textarea" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="是否默认" :label-width="100">
          <el-radio-group v-model="obj.is_default">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addCancel">取消</el-button>
          <el-button type="primary" @click="addCommit">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.delivery-addr-management {
  padding: 20px;
}

.demo-form-inline {
  margin-bottom: 20px;
}
</style>
